package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.Promotion;
import com.example.entity.PromotionRecord;
import com.example.entity.SecurityTipRecord;
import com.example.entity.authority.PartyUser;
import com.example.ext.entity.ExtPromotionRecord;
import com.example.mapp.PartyUserMapp;
import com.example.mapp.PromotionMapp;
import com.example.service.PromotionService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by douyx on 2018/03/18.
 */
@Service
public class PromotionServiceImpl implements PromotionService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(PromotionServiceImpl.class);

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private PartyUserMapp partyUserMapp;

	/**
	 * 阅读安全提示加积分
	 * 
	 * @param securityTipRecord
	 *            userId: 用户编号
	 *            type: 3 电梯安全管理员 4 维保员
	 *            tipId: 安全提示编号
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> addEmpiricByReadTip(SecurityTipRecord securityTipRecord) {
		try {
			String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
			securityTipRecord.setReadDt(date);
			SecurityTipRecord temp = promotionMapp.findReadTipRecord(securityTipRecord);
			if (null != temp && temp.getId() != null) {
				return ResultUtil.returnSuccess("成功", null);
			}

			promotionMapp.insertReadTipRecord(securityTipRecord);
			Map<String, Object> map = new HashMap<>();
			map.put("userId", securityTipRecord.getUserId());
			map.put("type", securityTipRecord.getType());
			Promotion promotion = promotionMapp.findById(map);
			if (null != promotion && promotion.getId() != null) {
				promotion = PromotionUtil.calc(promotion, securityTipRecord.getType(), 2, false);
				promotionMapp.update(promotion);
			} else {
				promotion = new Promotion();
				promotion.setType(securityTipRecord.getType());
				promotion.setUserId(securityTipRecord.getUserId());
				promotion = PromotionUtil.calc(promotion, securityTipRecord.getType(), 2, true);
				promotionMapp.insert(promotion);
			}
			PromotionRecord promotionRecord = new PromotionRecord();
			promotionRecord.setUserId(securityTipRecord.getUserId());
			promotionRecord.setType(securityTipRecord.getType());
			promotionRecord.setEmpiricItem("阅读一次安全提示");
			promotionRecord.setAddedTime(PromotionUtil.getTime());
			promotionRecord.setEmpiricValue(2);
			promotionMapp.insertRecord(promotionRecord);
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error("阅读安全提示加积分："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", null);
	}	
	
	/**
	 * 上传专业证书加经验
	 * 
	 * @param map
	 *            type: 3 电梯安全管理员 4 维保员 userId: 用户编号
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> addEmpiricByCert(Map<String, Object> map) {
		String type = (String) map.get("type");
		String userId = (String) map.get("userId");
		try {
			Promotion promotion = promotionMapp.findById(map);
			if (null != promotion && promotion.getId() != null) {
				if ("1".equals(promotion.getUserCert())) {
					return ResultUtil.returnSuccess("成功", null);
				}
				promotion = PromotionUtil.calc(promotion, type, 200, false);
				promotionMapp.update(promotion);
			} else {
				promotion = new Promotion();
				promotion.setType(type);
				promotion.setUserCert("1");
				promotion.setUserId(userId);
				promotion = PromotionUtil.calc(promotion, type, 200, true);
				promotionMapp.insert(promotion);
			}

			PromotionRecord promotionRecord = new PromotionRecord();
			promotionRecord.setUserId(userId);
			promotionRecord.setType(type);
			promotionRecord.setEmpiricItem("上传专业证书");
			promotionRecord.setAddedTime(PromotionUtil.getTime());
			promotionRecord.setEmpiricValue(200);
			promotionMapp.insertRecord(promotionRecord);

			PartyUser partyUser = partyUserMapp.findById(userId);
			if (null != partyUser && null != partyUser.getPartyId()) {
				if ("3".equals(type)) {
//					PromotionUtil.calcParty(promotionMapp, 2200, "2", Long.valueOf(partyUser.getPartyId()), "0");
					PromotionRecord promotionRecord1 = new PromotionRecord();
					promotionRecord1.setUserId(partyUser.getPartyId());
					promotionRecord1.setType("2");
					promotionRecord1.setEmpiricItem("上传专业证书");
					promotionRecord1.setAddedTime(PromotionUtil.getTime());
					promotionRecord1.setEmpiricValue(2200);
					promotionMapp.insertRecord(promotionRecord1);
				} else if ("4".equals(type)) {
//					PromotionUtil.calcParty(promotionMapp, 1200, "1", Long.valueOf(partyUser.getPartyId()), "0");
					PromotionRecord promotionRecord1 = new PromotionRecord();
					promotionRecord1.setUserId(partyUser.getPartyId());
					promotionRecord1.setType("1");
					promotionRecord1.setEmpiricItem("上传专业证书");
					promotionRecord1.setAddedTime(PromotionUtil.getTime());
					promotionRecord1.setEmpiricValue(1200);
					promotionMapp.insertRecord(promotionRecord1);
				}
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error("上传专业证书加经验："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", null);
	}

	/**
	 * 上传1份电梯安全管理制度中的资料
	 * 
	 * @param map
	 *            type: 1 维保单位 2 物业单位
	 *            partyId: 单位编号
	 *            empiricValue: 经验值
	 *            content: 加分项目
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> addByUpload(Map<String, Object> map) {
		String type = map.get("type") + "";
		String partyId = map.get("partyId") + "";
		String empiricValue = map.get("empiricValue") + "";
		String content = map.get("content") + "";
		try {
			PromotionUtil.calcParty(promotionMapp, Integer.valueOf(empiricValue), type, Long.valueOf(partyId), content, "0");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error("上传1份电梯安全管理制度中的资料："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", null);
	}

	/**
	 * 监管部门打分
	 * 
	 * @param map
	 *            type: 1 维保单位 2 物业单位
	 *            partyId: 单位编号
	 *            empiricValue: 经验值
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> addEmpiric(Map<String, Object> map) {
		String type = map.get("type") + "";
		String partyId = map.get("partyId") + "";
		String empiricValue = map.get("empiricValue") + "";
		try {
			PromotionUtil.calcParty(promotionMapp, Integer.valueOf(empiricValue), type, Long.valueOf(partyId), "监管部门打分", "0");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error("监管部门打分："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", null);
	}

	/**
	 * 用户转移经验同步转移
	 * 
	 * @param map
	 *            userId: 用户编号 (必输)
	 *            type: 3 电梯安全管理员 4 维保员  (必输)
	 *            partyIdBfr: 转移前机构编号 (必输)
	 *            partyTypeBfr: 1 维保单位 2 物业单位  (必输)
	 *            partyIdAft: 转移后机构编号 (必输)
	 *            partyTypeAft: 1 维保单位 2 物业单位  (必输)
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> empiricTrans(Map<String, Object> map) {
//		String partyTypeBfr =  map.get("partyTypeBfr")+"";
//		String partyTypeAft =  map.get("partyTypeAft")+"";
//		String partyIdBfr =  map.get("partyIdBfr")+"";
//		String partyIdAft = map.get("partyIdAft")+"";
		try {
//			Promotion promotion = promotionMapp.findById(map);
//			if (null != promotion && promotion.getId() != null) {
//				Integer empiricValue = promotion.getEmpiricValue();
//				PromotionUtil.calcParty(promotionMapp, - empiricValue, partyTypeBfr, Long.valueOf(partyIdBfr));
//				PromotionRecord promotionRecord1 = new PromotionRecord();
//				promotionRecord1.setUserId(partyIdBfr);
//				promotionRecord1.setType(partyTypeBfr);
//				promotionRecord1.setEmpiricItem("用户转移");
//				promotionRecord1.setAddedTime(PromotionUtil.getTime());
//				promotionRecord1.setEmpiricValue(- empiricValue);
//				promotionMapp.insertRecord(promotionRecord1);
//				PromotionUtil.calcParty(promotionMapp, empiricValue, partyTypeAft, Long.valueOf(partyIdAft));
//				PromotionRecord promotionRecord = new PromotionRecord();
//				promotionRecord.setUserId(partyIdAft);
//				promotionRecord.setType(partyTypeAft);
//				promotionRecord.setEmpiricItem("用户转移");
//				promotionRecord.setAddedTime(PromotionUtil.getTime());
//				promotionRecord.setEmpiricValue(empiricValue);
//				promotionMapp.insertRecord(promotionRecord);
//			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error("用户转移经验同步转移："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", null);
	}	

	/**
	 * 查询成就及经验值
	 * 
	 * @param map
	 *            type: 1 维保单位 2 物业单位 3 电梯安全管理员 4 维保员 userId: 用户编号/单位编号
	 * @return
	 */
	@Override
	public Map<String, Object> query(Map<String, Object> map) {
		String type = (String) map.get("type");
		Map<String, Object> result = new HashMap<>();
		try {
			Promotion promotion = promotionMapp.findById(map);
			if (null != promotion) {
				result.put("empiricValue", promotion.getEmpiricValue());
				result.put("grade", promotion.getGrade());
				if ("3".equals(type) || "2".equals(type)) {
					// 成就为List<String>
					result.put("achieves", PromotionUtil.getachieveList(promotion.getAchieve()));
				}
			}
		} catch (Exception e) {
			logger.error("查询成就及经验值："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", result);
	}

	/**
	 * 排行榜查询
	 * 
	 * @param map
	 *            type: 排名维度：1 维保单位 2 物业单位 3 电梯安全管理员 4 维保员 (必输) userId:
	 *            用户编号/单位编号 parentId: 需要查询下辖排行的区域单位编号(必输)
	 * @return userName: 用户名称 ranking: 排名 partyName: 单位名称 empiricValue: 经验值
	 *         grade: 等级 (单位无此字段) achieve: 成就 (单位无此字段) rankings:
	 *         排名列表（List<Map<String, Object>> 前十名 Map中包含上述字段）
	 */
	@Override
	public Map<String, Object> queryRanking(Map<String, Object> map) {
		String type = (String) map.get("type");
		Map<String, Object> result = new HashMap<>();
		try {
			if ("1".equals(type) || "2".equals(type)) {
				result = promotionMapp.findRankingParty(map);
				result.put("rankings", promotionMapp.findRankingPartyList(map));
			} else if ("3".equals(type) || "4".equals(type)) {
				result = promotionMapp.findRankingUser(map);
				result.put("rankings", promotionMapp.findRankingUserList(map));
			}
		} catch (Exception e) {
			logger.error("排行榜查询1："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", result);
	}

	/**
	 * 排行榜查询
	 * 
	 * @param map
	 *            type: 排名维度：1 维保单位 2 物业单位 3 电梯安全管理员 4 维保员 (必输)
	 * @return rankings: 排名列表（List<Map<String, Object>> 前十名 ）
	 *         userName: 用户名称 ranking: 排名 partyName: 单位名称 empiricValue: 经验值
	 *         grade: 等级 (单位无此字段) achieve: 成就 (单位无此字段)
	 */
	@Override
	public Map<String, Object> queryRanks(Map<String, Object> map) {
		String type = (String) map.get("type");
		Map<String, Object> result = new HashMap<>();
		try {
			if ("1".equals(type) || "2".equals(type)) {
				result.put("rankings", promotionMapp.findRanksPartyList(map));
			} else if ("3".equals(type) || "4".equals(type)) {
				result.put("rankings", promotionMapp.findRanksUserList(map));
			}
		} catch (Exception e) {
			logger.error("排行榜查询："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", result);
	}

	/**
	 * 查询加分记录
	 * 
	 * @param promotionRecord
	 *            type: 1 维保单位 2 物业单位 3 电梯安全管理员 4 维保员 (必输)
	 *            userId: 用户编号/单位编号(必输)
	 *            addedTimeFrom: 加分时间开始(可选)
	 *            addedTimeTo: 加分时间结束(可选)
	 * @return PromotionRecord
	 */
	@Override
	public Map<String, Object> queryRecord(ExtPromotionRecord promotionRecord) {
		Map<String, Object> map = new HashMap<>();
		try {
			if (null != promotionRecord.getCurrentPage() && null != promotionRecord.getPageSize()) {
				Page<PromotionRecord> page = PageHelper.startPage(promotionRecord.getCurrentPage(),
						promotionRecord.getPageSize());
				map.put("total", page.getTotal());
			}
			List<PromotionRecord> list = promotionMapp.findRecord(promotionRecord);
			map.put("list", list);
		} catch (Exception e) {
			logger.error("查询加分记录："+e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", map);
	}
}
